<script setup name="publishform">
import OAMain from '@/components/OAMain.vue';
import { ref, reactive, onMounted, shallowRef, onBeforeUnmount } from "vue"
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import staffHttp from '@/api/staffHttp';
import { ElMessage } from 'element-plus';
import { useAuthStore } from '@/stores/auth';
import informHttp from '@/api/informHttp';

const authstore = useAuthStore()

let informForm = reactive({
    title: '',
    content: '',
    department_ids: []
})

let rules = reactive({
    title: [
        { required: true, message: '标题是必填项', trigger: 'blur' },
    ],
    content: [
        { required: true, message: '通知内容是必填项', trigger: 'blur' },
    ],
    department_ids: [
        { required: true, message: '至少通知一个部门', trigger: 'change' },
    ],
})

let formRef = ref()
let formLabelWidth = "100PX"

let departments = ref([])
let mode = 'default'

/////////////////////// wangeditor配置
const editorRef = shallowRef()
// 模拟 ajax 异步获取内容,(需要自己实现)
// onMounted(() => {
//     setTimeout(() => {
//         valueHtml.value = '<p>模拟 Ajax 异步设置内容</p>'
//     }, 1500)
// })
const toolbarConfig = {}
const editorConfig = { 
    placeholder: '请输入内容...',
    MENU_CONF: {
        uploadImage: {
            server: import.meta.env.VITE_BASE_URL + '/image/upload',
            // 与后端保存一致
            fieldName: 'image',
            maxFileSize: 0.5 * 1024 * 1024 * 1024,
            maxNumberOfFiles: 10,
            allowedFileTypes: ['image/*'],
            headers: {
                Authorization: "JWT " + authstore.token
            },
            timeout: 1 * 1000 * 60, // 60 秒

            customInsert(res, insertFn) {   
                // res 即服务端的返回结果
                if(res.errno==0){
                    let data = res.data;
                    let url = import.meta.env.VITE_BASE_URL + data.url
                    let href = import.meta.env.VITE_BASE_URL + data.href
                    let alt = data.alt
                    // 从 res 中找到 url alt href ，然后插入图片
                    insertFn(url, alt, href)
                }else{
                    ElMessage.error(res.message)
                }
                
            },
            // 下面两个是错误处理回调,发生错误时会调用
            onFailed(file, res) {
                console.log(`${file.name} 上传失败`, res)
            },
            // 上传错误，或者触发 timeout 超时
            // 这个onError的触发机制应该和后端返回的errno值有关，未验证
            onError(file, err, res) {
                if(file.size > 50 * 1024){
                    ElMessage.error("图片大小不能超过2KB")
                }else{
                    // 是否是图片格式或者伪造的图片格式由后端校验
                    ElMessage.error("请上传正确格式的图片")
                }
            },    
                    }
    } }
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})
const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}
/////////////////////// wangeditor这里结束

const onSubmit = () => {
    // 先获取表单对象
    formRef.value.validate(async (valid, fields) => {
        if (valid) {
            try{
                await informHttp.publishInform(informForm)
            }catch(detaill){
                ElMessage.error(detail)
            }
        }
    })
}

onMounted(async () => {
    try{
        let data = await staffHttp.getAllDepartment()
        departments.value = data.results;
    }catch(detail){
        ElMessage.error(detail)
    }
})


</script>

<template>
    <OAMain title="发布通知">
        <el-card>
            <el-form :model="informForm" :rules="rules" ref="formRef">
                <el-form-item label="标题" :label-width="formLabelWidth" prop="title">
                    <el-input v-model="informForm.title" autocomplete="off" />
                </el-form-item>
                <el-form-item label="转发部门" :label-width="formLabelWidth" prop="department_ids">
                    <el-select multiple v-model="informForm.department_ids">
                        <el-option :value="0" label="all" />
                        <el-option v-for="department in departments" :label="department.name" :value="department.id"
                            :key="department.name" />
                    </el-select>
                </el-form-item>
                <el-form-item label="内容" :label-width="formLabelWidth" prop="content">
                    <div style="border: 1px solid #ccc; width: 100%">
                        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef"
                            :defaultConfig="toolbarConfig" :mode="mode" />
                        <Editor style="height: 500px; overflow-y: hidden;" v-model="informForm.content"
                            :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated" />
                    </div>
                </el-form-item>
                <el-form-item>
                    <div style="text-align: right; flex: 1;">
                        <el-button type="primary" @click="onSubmit">发送</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </el-card>
    </OAMain>
</template>
<style></style>